//
//  FlowlayoutView.swift
//  iFishApp
//
//  Created by Bob on 2022/3/5.
//

import SwiftUI

struct FlowlayoutView<Content: View, T: Identifiable>: View where T: Hashable {
    /// 数据源 一个泛型模型数组
    var list: [T]
    
    /// 指定一个content，后面会暴露在init方法中，用来自定义网格的每个item
    var content: (T) -> Content
    
    /// 网格列数
    var columns: Int
    
    /// item横向间距
    var itemSpacingH: CGFloat
    
    /// item纵向间距
    var itemSpacingV: CGFloat
    
    /// 对数据源重新组合
    private func splistList() -> [[T]] {
        var curIndex: Int = 0
        // 声明一个数组，该数组有columns个元素，每个元素类型为[T]
        var gridList: [[T]] = Array(repeating: [], count: columns)
        list.forEach { obj in
            gridList[curIndex].append(obj)
            if curIndex == columns - 1 {
                curIndex = 0
            } else {
                curIndex += 1
            }
        }
        return gridList
    }
    
    init(
        list: [T],
        columns: Int,
        itemSpacingH: CGFloat = 10,
        itemSpacingV: CGFloat = 10,
        @ViewBuilder content:
            @escaping (T) -> Content)
    {
        self.list = list
        self.columns = columns
        self.itemSpacingH = itemSpacingH
        self.itemSpacingV = itemSpacingV
        self.content = content
    }
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: /*@START_MENU_TOKEN@*/true/*@END_MENU_TOKEN@*/) {
            HStack(alignment: .top, spacing: itemSpacingH) {
                ForEach(splistList(), id:\.self) { objs in
                    LazyVStack(spacing: itemSpacingV) {
                        ForEach(objs) { obj in
                            content(obj)
                        }
                    }
                }
            }
        }
    }
}
